package cn.szsys.integration.constants;

import cn.szsys.integration.billrule.entity.BillingInfo;
import cn.szsys.integration.dos.BillingRuleDO;
import lombok.Getter;

import java.util.Arrays;
import java.util.List;

/**
 * @author Ryan
 * @since 2025-05-08
 **/
@Getter
public enum BillingRuleTypeEnum implements BillingRuleTypeReferee {
    /**
     * 1.固定(无论成功失败都计费)  2.响应码  3.响应时间
     */
    FIXED(1, "固定") {
        @Override
        public boolean isBilling(BillingInfo billingInfo, BillingRuleDO billingRuleDO) {
            return true;
        }
    },
    RESPONSE_CODE(2, "响应码") {
        @Override
        public boolean isBilling(BillingInfo billingInfo, BillingRuleDO billingRuleDO) {
            String[] codes = billingRuleDO.getCode().split(",");
            List<String> codeList = Arrays.asList(codes);
            //上游
            if (BillingRuleServiceTypeEnum.UPSTREAM.getCode() == billingRuleDO.getServiceType() && codeList.contains(billingInfo.getUpResponseCode())) {
                return true;
            }
            //下游
            if (BillingRuleServiceTypeEnum.DOWNSTREAM.getCode() == billingRuleDO.getServiceType() && codeList.contains(billingInfo.getDownResponseCode())) {
                return true;
            }
            return false;
        }
    },
    RESPONSE_TIME(3, "响应时间") {
        @Override
        public boolean isBilling(BillingInfo billingInfo, BillingRuleDO billingRuleDO) {
            long minimumVal = billingRuleDO.getMinimumVal().longValue();
            long maximumVal = billingRuleDO.getMaximumVal().longValue();
            //上游
            if (BillingRuleServiceTypeEnum.UPSTREAM.getCode() == billingRuleDO.getServiceType()
                    && minimumVal <= billingInfo.getUpResponseTime() && billingInfo.getUpResponseTime() <= maximumVal) {
                return true;
            }
            //下游
            if (BillingRuleServiceTypeEnum.DOWNSTREAM.getCode() == billingRuleDO.getServiceType()
                    && minimumVal <= billingInfo.getDownResponseTime() && billingInfo.getDownResponseTime() <= maximumVal) {
                return true;
            }
            return false;
        }
    };
    private final int code;
    private final String desc;

    BillingRuleTypeEnum(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public static BillingRuleTypeEnum getByCode(int code) {
        for (BillingRuleTypeEnum billingRuleTypeEnum : values()) {
            if (billingRuleTypeEnum.getCode() == code) {
                return billingRuleTypeEnum;
            }
        }
        return null;
    }
}
